package com.buhui.ecommerce.algorithm.QueuePractice;


//循环队列
public class CircularQueue <T>{
    int front;//头指针
    int tail;//尾指针
    int count;//队列存在元素的个数
    int queueLength=6;//队列容量，初始为6
    T arr[];
    CircularQueue (){
        arr= (T[]) new Object[queueLength];
    }
    CircularQueue(int customLength){
        queueLength=customLength;
        arr= (T[]) new Object[customLength];
    }

    //push 入队
    void push(T element){
        if(full()){
            System.out.println("队列已满，"+element+"无法入队");
            return;
        }
        arr[tail]=element;
        tail++;
        count++;

        if(tail == queueLength){
            tail=0;
        }
        System.out.println(element+"入队成功---此时头指针为："+front+"---此时尾指针为："+tail+"---此时队列存在元素个数为："+count+"---此时队列剩余空间为："+(queueLength-count));
        return;
    }
    //pop出队
    T pop(){
        if(empty()){
            System.out.println("当前队列为空，无法出队");
            return null;
        }
        count--;
        int pop=front++;

        if(front == queueLength){
            front=0;
        }
        System.out.println(arr[pop]+"出队成功---此时头指针为："+front+"---此时尾指针为："+tail+"---此时队列存在元素个数为："+count+"---此时队列剩余空间为："+(queueLength-count));

        return arr[pop];
    }

    //判空,true 为null
    boolean empty(){
        if(count == 0){
            return  true;
        }
        return false;
    }
    //判满,true为满
    boolean full(){
        if(count == queueLength){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println("        --------------------------------测试存储基本类型数据-------------------------------------------------\n");

        CircularQueue<Integer> circularQueue = new CircularQueue<Integer>();
        System.out.println("circularQueue 的容量为"+circularQueue.queueLength);
        for (int i = 0; i <9 ; i++) {
            circularQueue.push(i);
            circularQueue.pop();

        }

        System.out.println("        --------------------------------测试存储基本类型数据溢出-------------------------------------------------\n");

        for (int i = 0; i <7 ; i++) {
            circularQueue.push(i);
        }

        System.out.println("--------------------------------测试存储自定义类型数据-------------------------------------------------\n");
        CircularQueue<User> userQueue = new CircularQueue<User>(3);
        System.out.println("userQueue的容量为："+userQueue.queueLength);
        for (int i = 0; i <6 ; i++) {
            userQueue.push(new User(Integer.toString(i),Integer.toString(i)));
            userQueue.pop();
        }

        System.out.println("--------------------------------测试存储自定义类型数据溢出-------------------------------------------------\n");

        for (int i = 0; i <4 ; i++) {
            userQueue.push(new User(Integer.toString(i),Integer.toString(i)));
        }


    }
}


